import matplotlib.pyplot as plt
import pandas as pd
from DirMonitor import DirMonitor
from MeminfoFrameParser import MeminfoFrameParser


def handle_close(event):
    global df
    print('quit')


def update():
    global df
    added_files = dm.watch_changes()
    if len(added_files) == 0:
        return
    frames = MeminfoFrameParser.parse_files(added_files[:])
    df = df.append(frames)
    df = df.sort_index()
    df.plot(ax=ax, grid=True, figsize=(15, 9))
    # df_dvg = df.rolling(60, min_periods=1).mean()

    # ax.clear()
    # df_dvg.rename(columns={'dashcam': 'dashcam_avg', 'cpu_usage': 'cpu_usage_avg'}, inplace=True)
    # df_data = df.join(df_dvg)
    # df_data.plot(ax=ax, style=['--', '--', '-', '-'], subplots=True, layout=(4, 1))

    # ax.plot(df_data.index, df_data['dashcam'], lw=1, linestyle='--', color='#D3D3D3')
    # ax.plot(df_data.index, df_data['dashcam_avg'], lw=2, linestyle='-', color='#006400')
    # ax.plot(df_data.index, df_data['cpu_usage'], lw=1, linestyle='--', color='#D3D3D3')
    # ax.plot(df_data.index, df_data['cpu_usage_avg'], lw=2, linestyle='-', color='#8B0000')
    # df.plot(ax=ax, grid=True, style=['--', '-.'], subplots=True, layout=(2, 1))
    # df_dvg.plot(ax=ax, grid=True, style=['-', '-'], subplots=True, layout=(2, 1))
    # df.plot(ax=ax, grid=True, style=['--', '-.'])
    # plt.pause(1)
    plt.show()


if __name__ == '__main__':
    # plt.ion()
    fig = plt.figure()
    fig.canvas.mpl_connect('close_event', handle_close)
    ax = fig.add_subplot(111)  # Create an axes.

    df = pd.DataFrame()
    dm = DirMonitor('/media/ole/97a84aa2-5462-4774-821a-a45bc7efbf1a/home/ole/space2/20200408-3089/b3f00725/b3f00725')
    # while True:
    update()
    # plt.pause(10000)
